package com.magic.smartcity.view.more.metro.home

import android.os.Bundle
import android.view.*
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.snackbar.Snackbar
import com.magic.smartcity.R
import com.magic.smartcity.databinding.FragmentMetroHomeBinding
import com.magic.smartcity.view.more.adapters.MetroHomeLinesAdapter
import com.magic.smartcity.view.more.viewmodels.MetroViewModel

class MetroHomeFragment : Fragment() {
    private val TAG: String = "MetroFragment"

    private val location: String = "东直门"
    private lateinit var binding: FragmentMetroHomeBinding
    private val metroHomeLinesAdapter = MetroHomeLinesAdapter()


    private val metroModel by lazy {
        ViewModelProvider(this).get(MetroViewModel::class.java)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setHasOptionsMenu(true)
        /**
         * 请求数据
         */
        //获取地铁所有线路
        metroModel.requstMetroLineList()
        //获取当前站点的线路
        metroModel.getLinesByStationName(location)
        //获取经过当前站点线路，上一站和下一站
        metroModel.getCurrentStationDetail(location)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentMetroHomeBinding.inflate(layoutInflater, container, false)
        binding.toCard.setOnClickListener {
            Navigation.findNavController(it).navigate(R.id.metroCardFragment)
        }
        initView()
        initData()

        return binding.root
    }

    private fun initView() {
        binding.linesRvView.adapter = metroHomeLinesAdapter
        binding.linesRvView.setHasFixedSize(true)
        binding.linesRvView.layoutManager = LinearLayoutManager(context)

    }

    private fun initData() {
        metroModel.currentStationLinesDetail.observe(viewLifecycleOwner){
            metroHomeLinesAdapter.setData(location,it)
        }
        binding.location=location
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.metro_all_line, menu) //默认当前位置
        super.onCreateOptionsMenu(menu, inflater)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId==R.id.menu_metro_all_line) {//TODO:总览图跳转和显示b
//            Snackbar.make(requireView(),"点击了总览图", Snackbar.LENGTH_SHORT).show()
            Navigation.findNavController(requireView()).navigate(R.id.action_metroHomeFragment_to_metroHomeMapFragment)
        }
        return super.onOptionsItemSelected(item)
    }

}